package megalopolis.client;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

/**
 * User: Kirill
 * Date: 19.02.2008
 */
public class MainFrame extends JFrame implements ActionListener {

	private Controller controller;

	private JMenuItem fileConnect;

	private JMenuItem fileExit;

	public MainFrame(final Controller controller) {
		this.controller = controller;

		setTitle("Megalopolis Client");

		// create menu bar
		createMenuBar();

		// create game canvas
		Container contentPane = getContentPane();

		GameCanvas canvas = new GameCanvas(controller);
		contentPane.add(canvas);
		controller.setView(canvas);

		setSize(400, 300);

		addWindowListener(new WindowAdapter() {
			public void windowOpened(WindowEvent e) {
				showLoginDialog();
			}

			public void windowClosing(WindowEvent e) {
				controller.exit();
			}
		});
	}

	private void createMenuBar() {
		JMenuBar menuBar = new JMenuBar();

		JMenu fileMenu = new JMenu("File");
		fileConnect = new JMenuItem("Connect");
		fileConnect.addActionListener(this);
		fileMenu.add(fileConnect);
		fileExit = new JMenuItem("Exit");
		fileExit.addActionListener(this);
		fileMenu.add(fileExit);
		menuBar.add(fileMenu);

		setJMenuBar(menuBar);
	}

	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if (source == fileConnect) {
			showLoginDialog();
		} else if (source == fileExit) {
			controller.exit();
		}
	}

	private void showLoginDialog() {
		LoginDialog dialog = new LoginDialog(this, controller);
		dialog.setVisible(true);
	}

}
